package com.web.servlet;


import com.result.Result;
import com.result.ResultUtils;
import com.util.JsonUtils;
import com.util.ResponseUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@WebServlet(name = "UploadImage",urlPatterns = "/uploadImage")
@MultipartConfig(maxFileSize = 1024*1024*3)
public class UploadImage extends HttpServlet {


    private List<String> exts= Arrays.asList(".jpg",".png",".bmp");


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part part=req.getPart("image");
        if(part==null){
            System.out.println("没有携带图片...");
            Result result= ResultUtils.buildFail(5000,"没有携带图片");
            ResponseUtils.responseToJson(JsonUtils.writerValueAsString(result),resp);
            return;
        }

        String fileName=part.getSubmittedFileName();
        String ext=fileName.substring(fileName.lastIndexOf("."));

        if(!exts.contains(ext)){
            System.out.println("上传文件不合法");
            Result result= ResultUtils.buildFail(5000,"上传文件不合法");
            ResponseUtils.responseToJson(JsonUtils.writerValueAsString(result),resp);
            return;
        }

        String newFileName= UUID.randomUUID().toString()+ext;
        String path=getServletContext().getRealPath("img");
        File fi=new File(path);
        if(!fi.exists()){
            fi.mkdirs();
        }

        part.write(path+"/"+newFileName);

        Result result=ResultUtils.buildSuccess("http://localhost:8080/img/"+newFileName);
        ResponseUtils.responseToJson(JsonUtils.writerValueAsString(result),resp);

    }
}
